/* authentication related services */

var express = require('express')
var router = express.Router(),
    rp = require('request-promise'),
    request = require('request'),
    debug = require('debug')('react-demo'),
    multer = require('multer'),
    iconv = require('iconv-lite');

var upload = multer();

var configFile = 'config.'+process.env.NODE_ENV+'.json'
var config = require('../../config/'+configFile);

//上传账单 界面使用
router.post("/", function(req, res, next){
  var token = req.cookies.access_token
  var appId = req.cookies.appId;
  var param = req.body;
  param.appId = appId;
  var option = {
    method: 'POST',
    uri: config.apiHost+'/api/propertyBills/queryPropertyBillsView',
    body: param,
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }
  console.log(param)
  rp(option)
    .then(function(result) {
      debug(result);
      // var data = JSON.parse(result)
      if (result.success) {
        return res.json(result)
      }else {
        return res.status(500).json({
          success: false,
          errMsg: result.errMsg
        })
      }
    })
    .catch(function(err) {
      console.error(err);
      return res.status(err.statusCode).json({
        success: false,
        errCode: err.statusCode,
        errMsg: err.error?err.error.errMsg:err
      })
    })
})

router.post("/create", function(req, res, next){
  var token = req.cookies.access_token;
  var option = {
    method: 'POST',
    uri: config.apiHost+'/api/propertyBills/create',
    body: req.body,
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }

  rp(option)
    .then(function(result) {
      debug(result);
      // var data = JSON.parse(result)
      if (result.success) {
        return res.json(result)
      }else {
        return res.status(500).json({
          success: false,
          errMsg: result.errMsg
        })
      }
    })
    .catch(function(err) {
      console.error(err);
      return res.status(err.statusCode).json({
        success: false,
        errCode: err.statusCode,
        errMsg: err.error?err.error.errMsg:err
      })
    })
})


router.post("/pushMessage", function(req, res, next){
  var token = req.cookies.access_token;
  var appId = req.cookies.appId;
  var param = req.body;
  param.appId = appId;
  var option = {
    method: 'POST',
    uri: config.apiHost+'/api/propertyBills/pushMessage',
    body: param,
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }

  rp(option)
    .then(function(result) {
      debug(result);
      // var data = JSON.parse(result)
      if (result.success) {
        return res.json(result)
      }else {
        return res.status(500).json({
          success: false,
          errMsg: result.errMsg
        })
      }
    })
    .catch(function(err) {
      console.error(err);
      return res.status(err.statusCode).json({
        success: false,
        errCode: err.statusCode,
        errMsg: err.error?err.error.errMsg:err
      })
    })
})

router.post("/pushMessageAll", function(req, res, next){
  var token = req.cookies.access_token;
  var appId = req.cookies.appId;
  var param = req.body;
  param.appId = appId;
  var option = {
    method: 'POST',
    uri: config.apiHost+'/api/propertyBills/pushMessageAll',
    body: param,
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }

  rp(option)
    .then(function(result) {
      debug(result);
      // var data = JSON.parse(result)
      if (result.success) {
        return res.json(result)
      }else {
        return res.status(500).json({
          success: false,
          errMsg: result.errMsg
        })
      }
    })
    .catch(function(err) {
      console.error(err);
      return res.status(err.statusCode).json({
        success: false,
        errCode: err.statusCode,
        errMsg: err.error?err.error.errMsg:err
      })
    })
})

//上传账单
router.post("/upload", upload.single('media'), function(req, res, next) {

  var Converter = require("csvtojson").Converter;
  var converter = new Converter({
    noheader: true
  });

  var csvBuffer = req.file.buffer;
  var csvString = iconv.decode(csvBuffer, 'GBK')
  // var csvString = csvBuffer.toString('utf-8')
  // console.log(csvString)
  converter.fromString(csvString, function(err, result) {
    if (err) {
      console.error(err);
      debug(err)
      return res.json({
        success: false,
        errMsg: err.message,
        error: err
      })
    }

    var uploadData = [];
    for (var i = 0; i < result.length; i++) {
      var line = result[i];
      var amount = parseFloat(line.field4);
      console.log(amount)
      if (amount < 0) {
        return res.status(500).json({
          success: false,
          errMsg: '账单金额有负数,  请修改后重新上传!!'
        })
      }
      if (isNaN(amount)) {
        console.log("ignore");
      }else {
        uploadData.push(line)
      }
    }
    debug(uploadData)
    var token = req.cookies.access_token;
    var option = {
      method: 'POST',
      uri: config.apiHost+'/api/propertyBills/upload',
      body: {
        data: uploadData,
        appId: req.cookies.appId
      },
      headers: {
        authorization: 'Bearer '+token
      },
      json: true
    }
    rp(option)
      .then(function(result) {
        debug(result);
        // var data = JSON.parse(result)
        return res.json(result)
      })
      .catch(function(err) {
        console.error(err);
        debug(err)
        return res.status(err.statusCode).json({
          success: false,
          errCode: err.statusCode,
          errMsg: err.error?err.error.errMsg:err
        })
      })

  })

})

//账单管理内使用
router.post("/queryBillManager", function(req, res, next){
  var token = req.cookies.access_token
  var appId = req.cookies.appId;
  var param = req.body;
  param.appId = appId;
  var option = {
    method: 'POST',
    uri: config.apiHost+'/api/billManager/queryByTime',
    body: param,
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }
  console.log(param)
  rp(option)
    .then(function(result) {
      debug(result);
      // var data = JSON.parse(result)
      if (result.success) {
        return res.json(result)
      }else {
        return res.status(500).json({
          success: false,
          errMsg: result.errMsg
        })
      }
    })
    .catch(function(err) {
      console.error(err);
      return res.status(err.statusCode).json({
        success: false,
        errCode: err.statusCode,
        errMsg: err.error?err.error.errMsg:err
      })
    })
})

//导出csv
router.post("/export", function(req, res, next){
  var token = req.cookies.access_token
  var appId = req.cookies.appId;
  var param = req.body;
  param.appId = appId;
  var option = {
    method: 'POST',
    uri: config.apiHost+'/api/billManager/export',
    body: param,
    headers: {
      authorization: 'Bearer '+token
    },
    json: true
  }
  console.log(param)
  request(option)
  .on('error', (err) => {
    console.error(err);
    debug(err)
    return res.status(err.statusCode).json({
      success: false,
      errCode: err.statusCode,
      errMsg: err.error?err.error.errMsg:err
    })
  })
  .pipe(res)
})



module.exports = router;
